<script lang="ts" setup>
import {ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import useUserStore from '@/store/user.ts'
import InfoDialog from './InfoDialog.vue'
import PasswordDialog from './PasswordDialog.vue'
import Api from '@/api'

interface DialogExpose {
	openDialog: () => void
}

const userStore = useUserStore()
const infoRef = ref<null | DialogExpose>(null)
const passwordRef = ref<null | DialogExpose>(null)
// 打开修改密码和个人信息弹窗
const openDialog = (refName: string) => {
	if (refName === 'infoRef') infoRef.value?.openDialog()
	else passwordRef.value?.openDialog()
}

const logout = () => {
	ElMessageBox.confirm('您是否确认退出登录?', '温馨提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		Api.logoutApi().then((res: any) => {
			if (res.code !== 200) return
			userStore.userLogout()
			ElMessage.success('退出登录成功')
			setTimeout(() => {
				location.href = '/login'
			}, 1000)
		})
	}).catch(() => {
	})
}
</script>

<template>
	<el-dropdown>
		<div class="avatar">
			<img :src="userStore.avatar" alt="">
		</div>
		<template #dropdown>
			<el-dropdown-menu>
				<el-dropdown-item @click="openDialog('infoRef')">
					<el-icon>
						<User/>
					</el-icon>
					个人信息
				</el-dropdown-item>
				<el-dropdown-item @click="openDialog('passwordRef')">
					<el-icon>
						<Edit/>
					</el-icon>
					修改密码
				</el-dropdown-item>
				<el-dropdown-item divided @click="logout">
					<el-icon>
						<SwitchButton/>
					</el-icon>
					退出登录
				</el-dropdown-item>
			</el-dropdown-menu>
		</template>
	</el-dropdown>

	<!--个人信息-->
	<InfoDialog ref="infoRef"/>
	<!--修改密码-->
	<PasswordDialog ref="passwordRef"/>
</template>

<style lang="scss" scoped>
.avatar {
	width: 40px;
	height: 40px;
	overflow: hidden;
	cursor: pointer;
	border-radius: 50%;

	img {
		width: 100%;
		height: 100%;
	}
}
</style>
